import { CloseCircleFilled } from "@ant-design/icons";
import { Divider, Input, Modal, Typography } from "antd";
import { useEffect, useMemo, useState } from "react";
import useCategoryTree from "../use_category_tree";

export function useAddProduct() {
  const [isVis, setIsVis] = useState(false);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const [sureSelectedRows, setSureSelectedRow] = useState<any[]>([]);
  const [keyWords, setKeyWords] = useState(undefined);
  const {
    currentId,
    setCurrentId,
    render: renderCategoryTree,
  } = useCategoryTree<ProductCategory>({
    modalType: "",
    isMore: false,
    nodeIdKey: "product_category_id",
    api: ListProductCategory,
  });

  const {
    tableProps,
    loading,
    search: runListProduct,
  } = usePaginationQuery<Product>({
    service: ListProduct,
    initSearchParams: {
      q: keyWords,
      need_stock_quantity: true,
    },
  });

  const columns = [
    {
      title: "商品编码",
      dataIndex: "encoding",
      search: false,
    },
    {
      title: "商品名称",
      dataIndex: "name",
      fieldProps: {
        placeholder: "搜索商品名称/编码",
      },
    },
    {
      title: "规格型号",
      dataIndex: "model",
      search: false,
    },
    {
      title: "基本单位",
      dataIndex: "base_unit_name",
      search: false,
    },
  ];

  const handleCancel = () => {
    setSelectedRows([]);
    setIsVis(false);
  };

  const clearItem = (id?: number) => {
    if (!id) {
      setSelectedRows([]);
    } else {
      const newSelectedRows = selectedRows.filter((f) => f.product_id !== id);
      setSelectedRows(newSelectedRows);
    }
  };

  const handleOk = () => {
    setSureSelectedRow(selectedRows);
    setIsVis(false);
  };

  const onSelectChange = (_: any, selectedRows: Product[]) => {
    const selectData = selectedRows.map((item: any) => {
      return {
        ...item,
        aux_unit_id: +item.aux_unit_id ? item.aux_unit_id : item?.base_unit,
        business_unit_id: +item?.stock_unit!
          ? item?.stock_unit!
          : item?.base_unit!,
      };
    });
    setSelectedRows(selectData);
  };

  const rowSelection = {
    preserveSelectedRowKeys: true,
    selectedRowKeys: selectedRows.map((k) => k.product_id),
    onChange: onSelectChange,
    getCheckboxProps: () => ({
      disabled: false,
    }),
  };

  const openAdd = () => {
    setIsVis(true);
    runListProduct({
      category_ids: !["0"].includes(currentId) ? [currentId] : [],
      q: keyWords ? keyWords : undefined,
    });
  };

  /** 按分类查找商品 */
  useEffect(() => {
    runListProduct({
      category_ids: !["0"].includes(currentId) ? [currentId] : [],
      q: keyWords ? keyWords : undefined,
    });
  }, [currentId]);

  const renderAddModal = useMemo(() => {
    return (
      <Modal
        title="添加商品"
        onOk={handleOk}
        onCancel={handleCancel}
        open={isVis}
        destroyOnClose={true}
        afterClose={() => {
          setCurrentId("0");
          setKeyWords(undefined);
          setSelectedRows([]);
        }}
        width={"90%"}
        footer={(_, { OkBtn, CancelBtn }) => (
          <div className="flex justify-between">
            <div></div>
            <div>
              <CancelBtn />
              <OkBtn />
            </div>
          </div>
        )}
      >
        <div
          className="flex"
          style={{
            borderBottom: "1px solid #eee",
            height: "60vh",
            overflowY: "scroll",
          }}
        >
          <div
            style={{
              borderRight: "1px solid #eee",
              width: 246,
              boxSizing: "border-box",
            }}
          >
            <Divider className="m-0 border-[#EBEBEB]" />
            {renderCategoryTree}
          </div>
          <div className="flex flex-1" style={{ borderTop: "1px solid #eee" }}>
            <div className="p-[16px] flex-1">
              <Input.Search
                style={{ width: "30%" }}
                placeholder="搜索商品名称/编码"
                // value={keyWords}
                onSearch={(value: any) => {
                  runListProduct({
                    category_ids: !["0"].includes(currentId) ? [currentId] : [],
                    q: value ? value : undefined,
                  });
                  setKeyWords(value);
                }}
              />
              <ProTable
                className="flex flex-col mt-[16px]"
                loading={loading}
                renderEmptyContent="-"
                rowKey="product_id"
                {...tableProps}
                columns={columns}
                scroll={{ y: "calc(60vh - 180px)" }}
                rowSelection={rowSelection}
              />
            </div>
            <div
              className="p-[16px]"
              style={{
                borderLeft: "1px solid #eee",
                width: 200,
                flexShrink: 0,
              }}
            >
              <div className="flex justify-between items-center">
                <Typography.Text strong className="text-[16px]">
                  已选（{selectedRows.length}）
                </Typography.Text>
                <span onClick={() => clearItem()} className="text-[#0363FF]">
                  清除
                </span>
              </div>
              {selectedRows?.map?.((item, index) => {
                return (
                  <div
                    key={index}
                    className="flex justify-between items-center py-[9px]"
                  >
                    <Typography.Text>{item.name}</Typography.Text>
                    <CloseCircleFilled
                      onClick={() => clearItem(item?.product_id)}
                      className="text-[#c2c2c2] cursor-pointer"
                    />
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </Modal>
    );
  }, [isVis, selectedRows, tableProps.dataSource]);

  return {
    renderAddModal,
    openAdd,
    sureSelectedRows,
  };
}
